package com.mwx.loseweight.common.utils;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mwx.loseweight.mapper.UserMapper;
import com.mwx.loseweight.pojo.entity.User;
import com.mwx.loseweight.pojo.vo.UserLoginVO;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;

/**
 * 当前登录信息工具类
 */
@Component
public class LoginUserUtils {
	
	@Autowired
	private UserMapper userMapper;

	/*
	 * 获取当前登录的用户
	*/
	@SneakyThrows
    public User getLoginUser(HttpServletRequest request) {
    	 Cookie[] cookies = request.getCookies();
         if (cookies != null) {
             for (Cookie cookie : cookies) {
                 // 查找名为"userInfo"的Cookie
                 if ("userInfo".equals(cookie.getName())) {
                     // 解码Cookie值
                     String encodedUserInfo = cookie.getValue();
                     String userInfoString = URLDecoder.decode(encodedUserInfo, StandardCharsets.UTF_8);
                     // 将字符串转换为UserLoginVO对象
                     ObjectMapper objectMapper = new ObjectMapper();
                     UserLoginVO userLoginVO = objectMapper.readValue(userInfoString, UserLoginVO.class);
                     // 设置用户信息到上下文
                     Long userId = userLoginVO.getId();
                     if (userId == null) {
                         return new User();
                     }
                     // 查询数据库是否存在该用户
                     User user = userMapper.selectById(userId);
                     if (user == null) {
                         return new User();
                     }
                     return user;
                 }
             }
         }
    	return new User();
    }

}
